package com.liuzhu.chaoshikucungunli.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.liuzhu.chaoshikucungunli.R;
import com.liuzhu.chaoshikucungunli.adapter.ProductAdapter;
import com.liuzhu.chaoshikucungunli.adapter.BannerAdapter;
import com.liuzhu.chaoshikucungunli.model.Product;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Handler;
import android.os.Looper;
import java.util.ArrayList;
import java.util.List;
import android.widget.LinearLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.liuzhu.chaoshikucungunli.db.ProductDao;
import android.app.AlertDialog;
import android.net.Uri;
import android.widget.Toast;
import android.widget.VideoView;
import android.media.MediaPlayer;
import android.widget.SeekBar;
import java.util.Locale;
import android.widget.ImageButton;

public class HomeFragment extends Fragment {
    
    private RecyclerView recyclerView;
    private ProductAdapter adapter;
    private EditText searchEditText;
    private ViewPager2 bannerViewPager;
    private Handler handler;
    private static final long BANNER_DELAY = 3000; // 轮播间隔时间
    private ProductDao productDao;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        
        initViews(view);
        setupRecyclerView();
        setupBanner(view);
        productDao = new ProductDao(requireContext());
        loadTestData();
        
        return view;
    }
    
    private void initViews(View view) {
        recyclerView = view.findViewById(R.id.products_recycler_view);
        searchEditText = view.findViewById(R.id.search_edit_text);
        bannerViewPager = view.findViewById(R.id.banner_view_pager);
    }
    
    private void setupRecyclerView() {
        adapter = new ProductAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);

        // 设置视介绍点击监听
        adapter.setOnProductIntroClickListener(product -> {
            // 创建并显示视频播放对话框
            showVideoDialog(product);
        });
    }
    
    private void setupBanner(View rootView) {
        List<BannerAdapter.BannerItem> bannerItems = new ArrayList<>();
        bannerItems.add(new BannerAdapter.BannerItem(R.drawable.lbt1, "热销商品"));
        bannerItems.add(new BannerAdapter.BannerItem(R.drawable.lbt2, "热销商品"));
        bannerItems.add(new BannerAdapter.BannerItem(R.layout.banner_sales_stats, "今日销售/进货统计", true));
        
        BannerAdapter bannerAdapter = new BannerAdapter(bannerItems);
        bannerViewPager.setAdapter(bannerAdapter);
        
        // 设置指示器
        setupIndicators(bannerItems.size(), rootView);
        
        // 自动轮播
        handler = new Handler(Looper.getMainLooper());
        bannerViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                updateIndicators(position);
                handler.removeCallbacksAndMessages(null);
                handler.postDelayed(bannerRunnable, BANNER_DELAY);
                
                // 当换到统计页面时更新数据
                if (position == 2) {
                    updateSalesStats();
                }
            }
        });
        
        // 添加页面转换动画
        bannerViewPager.setPageTransformer(new ViewPager2.PageTransformer() {
            private static final float MIN_SCALE = 0.85f;
            private static final float MIN_ALPHA = 0.5f;
            
            @Override
            public void transformPage(@NonNull View view, float position) {
                int pageWidth = view.getWidth();
                int pageHeight = view.getHeight();

                if (position < -1) { // [-Infinity,-1)
                    // This page is way off-screen to the left.
                    view.setAlpha(0f);
                } else if (position <= 1) { // [-1,1]
                    // Modify the default slide transition to shrink the page as well
                    float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
                    float vertMargin = pageHeight * (1 - scaleFactor) / 2;
                    float horzMargin = pageWidth * (1 - scaleFactor) / 2;
                    if (position < 0) {
                        view.setTranslationX(horzMargin - vertMargin / 2);
                    } else {
                        view.setTranslationX(-horzMargin + vertMargin / 2);
                    }

                    // Scale the page down (between MIN_SCALE and 1)
                    view.setScaleX(scaleFactor);
                    view.setScaleY(scaleFactor);

                    // Fade the page relative to its size.
                    view.setAlpha(MIN_ALPHA +
                            (scaleFactor - MIN_SCALE) /
                            (1 - MIN_SCALE) * (1 - MIN_ALPHA));
                } else { // (1,+Infinity]
                    // This page is way off-screen to the right.
                    view.setAlpha(0f);
                }
            }
        });
    }
    
    private void setupIndicators(int count, View rootView) {
        LinearLayout indicatorContainer = rootView.findViewById(R.id.indicator_container);
        ImageView[] indicators = new ImageView[count];
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(8, 0, 8, 0);
        
        for (int i = 0; i < count; i++) {
            indicators[i] = new ImageView(getContext());
            indicators[i].setImageDrawable(
                    getResources().getDrawable(i == 0 ? 
                            R.drawable.indicator_selected : 
                            R.drawable.indicator_unselected, null));
            indicators[i].setLayoutParams(params);
            indicatorContainer.addView(indicators[i]);
        }
    }
    
    private void updateIndicators(int position) {
        View rootView = bannerViewPager.getRootView();
        LinearLayout indicatorContainer = rootView.findViewById(R.id.indicator_container);
        if (indicatorContainer == null) return;
        
        int count = indicatorContainer.getChildCount();
        for (int i = 0; i < count; i++) {
            ImageView indicator = (ImageView) indicatorContainer.getChildAt(i);
            indicator.setImageDrawable(
                    getResources().getDrawable(i == position ? 
                            R.drawable.indicator_selected : 
                            R.drawable.indicator_unselected, null));
        }
    }
    
    private final Runnable bannerRunnable = new Runnable() {
        @Override
        public void run() {
            int currentItem = bannerViewPager.getCurrentItem();
            bannerViewPager.setCurrentItem((currentItem + 1) % 3);
        }
    };
    
    @Override
    public void onResume() {
        super.onResume();
        handler.postDelayed(bannerRunnable, BANNER_DELAY);
    }
    
    @Override
    public void onPause() {
        super.onPause();
        handler.removeCallbacksAndMessages(null);
    }
    //TODO 数据获取方式
    private void loadTestData() {
        List<Product> products = productDao.getAllProducts();
        // 设置对应的图片资源
        for (Product product : products) {
            switch (product.getCode()) {
                case "P001":
                    product.setImageResId(R.drawable.produce1);
                    break;
                case "P002":
                    product.setImageResId(R.drawable.produce2);
                    break;
                case "P003":
                    product.setImageResId(R.drawable.produce3);
                    break;
                case "P004":
                    product.setImageResId(R.drawable.produce4);
                    break;
            }
        }
        adapter.setProducts(products);
    }
    
    // 添加更新销售统计数据的方法
    private void updateSalesStats() {
        View statsView = bannerViewPager.findViewWithTag("stats_view");
        if (statsView != null) {
            TextView salesAmount = statsView.findViewById(R.id.sales_amount);
            TextView salesCount = statsView.findViewById(R.id.sales_count);
            TextView purchaseAmount = statsView.findViewById(R.id.purchase_amount);
            TextView purchaseCount = statsView.findViewById(R.id.purchase_count);
            
            // TODO: 从数据库或其他数据源获取实际数据
            salesAmount.setText("¥1234.56");
            salesCount.setText("12件");
            purchaseAmount.setText("¥2345.67");
            purchaseCount.setText("23件");
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (bannerViewPager != null) {
            bannerViewPager.unregisterOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {});
        }
    }
    
    private void showVideoDialog(Product product) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_video_player, null);
        
        VideoView videoPlayer = dialogView.findViewById(R.id.video_player);
        ImageButton playPauseButton = dialogView.findViewById(R.id.btn_play_pause);
        SeekBar progressBar = dialogView.findViewById(R.id.video_progress);
        TextView currentTimeText = dialogView.findViewById(R.id.current_time);
        TextView totalTimeText = dialogView.findViewById(R.id.total_time);
        TextView titleText = dialogView.findViewById(R.id.video_title);
        
        // 创建对话框
        AlertDialog dialog = builder.setView(dialogView).create();
        
        // 设置标题
        titleText.setText(product.getName() + "介绍视频");
        
        // 根据商品名称获取对应的视频文件名
        String videoFileName = "";
        String productName = product.getName().toLowerCase();
        if (productName.contains("面包")) {
            videoFileName = "video_bread";
        } else if (productName.contains("可乐")) {
            videoFileName = "video_cola";
        } else if (productName.contains("牛奶")) {
            videoFileName = "video_milk";
        } else if (productName.contains("豆奶")) {
            videoFileName = "video_soymilk";
        }
        
        // 设置视频路径
        String videoPath = "android.resource://" + requireContext().getPackageName() + "/raw/" + videoFileName;
        videoPlayer.setVideoURI(Uri.parse(videoPath));
        
        // 设置进度条
        videoPlayer.setOnPreparedListener(mp -> {
            progressBar.setMax(mp.getDuration());
            totalTimeText.setText(formatTime(mp.getDuration()));
            mp.start();
        });
        
        // 更新进度
        Handler handler = new Handler();
        Runnable updateProgress = new Runnable() {
            @Override
            public void run() {
                if (videoPlayer.isPlaying()) {
                    int currentPosition = videoPlayer.getCurrentPosition();
                    progressBar.setProgress(currentPosition);
                    currentTimeText.setText(formatTime(currentPosition));
                    handler.postDelayed(this, 1000);
                }
            }
        };
        
        // 播放/暂停按钮点击事件
        playPauseButton.setOnClickListener(v -> {
            if (videoPlayer.isPlaying()) {
                videoPlayer.pause();
                playPauseButton.setImageResource(R.drawable.ic_play);
                handler.removeCallbacks(updateProgress);
            } else {
                videoPlayer.start();
                playPauseButton.setImageResource(R.drawable.ic_pause);
                handler.post(updateProgress);
            }
        });
        
        // 进度条拖动事件
        progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    videoPlayer.seekTo(progress);
                    currentTimeText.setText(formatTime(progress));
                }
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                videoPlayer.pause();
                handler.removeCallbacks(updateProgress);
            }
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                videoPlayer.start();
                handler.post(updateProgress);
            }
        });
        
        // 关闭按钮点击事件
        dialogView.findViewById(R.id.btn_close).setOnClickListener(v -> {
            videoPlayer.stopPlayback();
            handler.removeCallbacks(updateProgress);
            dialog.dismiss();
        });
        
        // 开始播放时启动进度更新
        videoPlayer.setOnInfoListener((mp, what, extra) -> {
            if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                handler.post(updateProgress);
                return true;
            }
            return false;
        });
        
        // 设置对话框全屏显示
        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
    }
    
    // 格式化时间
    private String formatTime(int milliseconds) {
        int seconds = milliseconds / 1000;
        int minutes = seconds / 60;
        seconds = seconds % 60;
        return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
    }
} 